package com.momo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.momo.configuration.open.EmojiFilter;
import com.momo.res.wx.ScanReturnInfo;
import com.momo.res.wx.WxInfo;
import com.momo.utils.HttpUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Kagome on 2019/5/21.
 */
public class CallBckAddressController {
    // 千万要记住，这个是微信开放平台的APPID
    String WX_PLATFROM_APPID = "XXXXXXXXX";
    // 千万要记住，这个是微信开放平台的APPSECRET
    String WX_PLATFORM_APPSECRET = "XXXXXXXXXX";
    // 拉起微信扫码页地址
    String WX_SCAN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    // 微信扫码之后获取用户基本信息的地址
    String WX_SCAN_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    /**
     * 微信扫码登录回调
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "wxLoginCallback", method = RequestMethod.GET)
    public void loginCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        if (code == null) {
            // 用户禁止授权
        }
        String url = WX_SCAN_URL.replace("APPID", WX_PLATFROM_APPID).replace("SECRET", WX_PLATFORM_APPSECRET)
                .replaceAll("CODE", code);
        url = response.encodeURL(url);
        try {
            String result = HttpUtils.doGet(url);
            JSONObject.toJSON(result);
            WxInfo wxInfo= JSON.parseObject(result, new TypeReference<WxInfo>() {
            });

            // 这里可以根据获取的信息去库中判断是否存在库中 如果不存在执行以下方法
            // 如果该用户不存在数据库中
            // 获取用户信息
            url = WX_SCAN_GET_USER_INFO.replace("ACCESS_TOKEN", wxInfo.getAccess_token()).replace("OPENID", wxInfo.getOpenid());
            url = response.encodeURL(url);
            String userResult = HttpUtils.doGet(url);
            ScanReturnInfo scanReturnInfo= JSON.parseObject(result, new TypeReference<ScanReturnInfo>() {
            });
//            Map<String, Object> userResultMap = JsonHelper.toMap(userResult);
            // 注册一个用户
            System.out.println("扫码登录返回值******************:" + userResult);
//            String headimgurl = (String) userResultMap.get("headimgurl");
            // 处理微信名特殊符号问题 过滤图标
//            String nickname = (String) userResultMap.get("nickname");
            String nickname = EmojiFilter.filterEmoji(scanReturnInfo.getNickname());
            // 把用户信息存入session中
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回地址
        try {
            String newUrl = request.getParameter("state");
            response.sendRedirect(newUrl);
        } catch (IOException e) {
            // logger.error("url:重定向错误");
        }
    }
}
